from django import template
from django.template.base import Template
from django.template.context import Context
from django.template.loader import render_to_string
from django.conf import settings
from apps.comments.models import CommentNotification
from apps.news.models import Record
from ..models import Comment

register = template.Library()

@register.simple_tag
def comment_record_url(comment):
    record = Record.objects.get(pk = comment.uid)
    return "<a href='%s%s' target='_blank'>%s</a>" % (settings.LIVE_ENGINE_URL, record.get_page_url(), record.title)

@register.simple_tag
def record_comments(user):
    notifications = CommentNotification.objects.filter(user = user)
    return render_to_string(
        "%s/%s" % (settings.LIVE_ENGINE_TEMPLATE, "comments/record_comments.html"),
            {
            'notifications': notifications
        }
    )
@register.simple_tag
def last_comments():
    comments = Comment.objects.filter(status=Comment.STATUS_PUBLISHED).order_by("-date")[:5]

    for comment in comments:
        for key in comment.SMILES:
            str = ":%s:" % key
            replace = "<img src='%s' />" % comment.SMILES.get(key)
            comment.message = comment.message.replace(str, replace)

    return render_to_string(
        "%s/%s" % (settings.LIVE_ENGINE_TEMPLATE, "comments/last_comments.html"),
        {
            'comments': comments
        }
    )

@register.simple_tag
def user_comments_count(user):
    count = Comment.objects.filter(user=user).count()
    return "%s" % count

@register.simple_tag
def comments_count(uid):
    count = Comment.objects.filter(uid=uid).count()
    return "%s" % count

@register.simple_tag
def render_comment(comment):

    comment.message = comment.message.replace("<", "&lt;")
    comment.message = comment.message.replace(">", "&gt;")

    for key in comment.SMILES:
        str = ":%s:" % key
        replace = "<img src='%s' />" % comment.SMILES.get(key)
        comment.message = comment.message.replace(str, replace)

    return render_to_string(
        "%s/%s" % (settings.LIVE_ENGINE_TEMPLATE, "comments/comment.html"),
        {
            'comment': comment
        }
    )

@register.simple_tag
def comments(unique_id, user):

    comments = Comment.objects.filter(
        uid = unique_id,
        status = Comment.STATUS_PUBLISHED,
        parent = None
    )

    return render_to_string(
        "%s/%s" % (settings.LIVE_ENGINE_TEMPLATE, "comments/list.html"),
        {
            'comments': comments,
            'uid': unique_id,
            'user': user
        }
    )

